package com.search.server.impl;

import com.search.server.SearchServiceGrpc;
import com.search.server.SearchServiceProto;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Tequila
 * @date 2022/5/7 14:56
 */
public class SearchServiceImpl extends SearchServiceGrpc.SearchServiceImplBase {

    private final int port = 9999;
    private Server server;

    @Override
    public void search(SearchServiceProto.SearchRequest request, StreamObserver<SearchServiceProto.SearchResponse> responseObserver) {
        if (request.isInitialized()) {
            System.out.println("true");
        }
        int value = request.getCorpusValue();
        int pageNumber = request.getPageNumber();
        String query = request.getQuery();
        int resultPerPage = request.getResultPerPage();
        System.out.println(request.toString());
        /*
         * proto Data
         * */
        List<SearchServiceProto.Data> datas = new ArrayList<>();
        datas.add(SearchServiceProto.Data.newBuilder().setDataInt(1).setDataStr("一").build());

        SearchServiceProto.SearchResponse build = SearchServiceProto.SearchResponse.newBuilder()
                // 如果用到了repeated修饰的proto message则不可使用set进行赋值用add
                .setCode(200)
                .setMsg("通信成功")
                .addAllData(datas)
                .build();

        responseObserver.onNext(build);
        // 结束
        responseObserver.onCompleted();
    }

    public void start() throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(new SearchServiceImpl())
                .build()
                .start();
        System.out.println("service start...at port" + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                SearchServiceImpl.this.stop();
                System.out.println("程序出错或正常退出！");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    /**
     * 不让main线程断开
     * @throws InterruptedException
     */
    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

}

